import React, { useEffect, useState } from 'react';
import { history, connect } from 'umi';
import { getTime } from '@/utils/time';
import {
  FooterToolbar,
  ProForm,
  ProFormCheckbox,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import './ist.css';
import { Button, Form, message, Modal, Upload, UploadProps } from 'antd';
import AMapLoader from '@amap/amap-jsapi-loader';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { RcFile, UploadChangeParam, UploadFile } from 'antd/es/upload';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

let map = null;
function EditHouse(props: any) {
  console.log(props);

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 编辑器内容
  const [html, setHtml] = useState('<p>hello</p>');

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setTimeout(() => {
      setHtml('<p>hello world</p>');
    }, 1500);
  }, []);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...',
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  const [form] = Form.useForm();
  // const [list, setList] = useState({});
  const id = history.location.state?.id;

  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const loca = () => {
    showModal();
    AMapLoader.load({
      key: 'd7d087c06b1c235fb99f45f3e00ea946', // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    })
      .then((AMap) => {
        map = new AMap.Map('container', {
          center: [105.602725, 37.076636], //初始化地图中心点位置
        });
      })
      .catch((e) => {
        console.log(e);
      });
  };
  useEffect(() => {
    props.dispatch({ type: 'house/EDIT', id });
  }, []);

  form.setFieldsValue({
    ...props.list,
    opening_time: getTime(props.list.opening_time),
    complate_time: getTime(props.list.complate_time),
  });

  const setLlll = (values: any) => {
    values.ordid = props.list.ordid;
    values.id = props.list.id;
    props.dispatch({ type: 'house/SET', values });
    history.push('/home/house/housecontrol/list');
  };
  return (
    <div className="form">
      <ProForm
        form={form}
        submitter={{
          render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
        }}
        onFinish={async (values) => setLlll(values)}
      >
        <ProForm.Group>
          <ProFormText name="title" label="楼盘名称" placeholder="请输入名称" />
          <div className="pri">
            <ProFormText name="price" label="均价" />
          </div>
          <div className="select-ant">
            <ProFormSelect
              options={[
                {
                  value: 'chapter',
                  label: '元/㎡',
                },
                {
                  value: 'chapter',
                  label: '万/套',
                },
              ]}
              width="xs"
              name="chapter"
            />
          </div>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            name="address"
            label="楼盘地址"
            placeholder="请输入名称"
          />
          <ProFormText
            name="address"
            label="售楼处地址"
            placeholder="请输入名称"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="opening_time" label="开盘时间" />
          <ProFormText name="complate_time" label="交房时间" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="sale_phone" label="售楼电话" />
          <ProFormText name="sale_phone_item" />
          <ProFormText name="pre_sale" label="预售证号" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            name="developer_name"
            label="开发商"
            placeholder="请输入名称"
          />
          <ProFormText name="map" label="地图坐标" placeholder="请输入名称" />
          <Button onClick={() => loca()}>标注位置</Button>
        </ProForm.Group>
        <ProFormCheckbox.Group
          name="cheap_house"
          label="优惠楼盘"
          options={['']}
        />
        <ProFormTextArea width="xl" label="优惠内容" name="remark" />
        <ProFormRadio.Group
          label="装修情况"
          name="build"
          // initialValue="发票"
          options={['毛胚', '简装', '精装', '豪装', '发多少']}
        />
        <ProFormRadio.Group
          label="销售状态"
          name="sale-status"
          // initialValue="发票"
          options={['在售', '新盘', '尾盘', '售罄', '未开盘']}
        />
        <ProFormCheckbox.Group
          name="house-category"
          label="楼盘类型"
          // initialValue="发票"
          options={['住宅', '别墅', '商铺', '写字楼', '公寓', '底商']}
        />
        <ProFormCheckbox.Group
          name="special-tags"
          label="特色标签"
          // initialValue="发票"
          options={[
            '小户型',
            '低密居所',
            '旅游地产',
            '教育地产',
            '宜居生态',
            '公园地产',
            '海景楼盘',
            '养生社区',
            '精装楼盘',
            '品牌楼盘',
            '发多少',
          ]}
        />
        <ProFormCheckbox.Group
          name="recommend"
          label="推荐位"
          // initialValue="发票"
          options={[
            '首页热销楼盘',
            '首页热盘推荐',
            '首页刚需推荐',
            '新房列表推荐',
          ]}
        />
        <Form.Item
          label="缩略图"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
            ) : (
              uploadButton
            )}
          </Upload>
          <img
            className="imgss"
            src={`http://fangadmin.shbwyz.com${props.list.img}`}
            alt=""
          />
        </Form.Item>
        <ProFormText
          name="all-look"
          label="全景看房"
          placeholder="请输入名称"
        />
      </ProForm>

      <Form.Item label="楼盘介绍">
        <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: '1px solid #ccc' }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: '200px', overflowY: 'hidden' }}
          />
        </div>
      </Form.Item>
      <Modal
        title="地图"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div id="container" style={{ width: '500px', height: '400px' }}></div>
      </Modal>
    </div>
  );
}

const mapStateToProps = (state: any) => {
  console.log(state);
  return {
    list: state.house.editList,
  };
};
export default connect(mapStateToProps)(EditHouse);
